package main

import (
	"fmt"
)

/**
执行用时：0 ms, 在所有 Go 提交中击败了100.00%的用户
内存消耗：2.1 MB, 在所有 Go 提交中击败了62.63%的用户
 */
func generateMatrix(n int) [][]int {

	res := make([][]int, n)
	for i := 0; i < n; i++ { res[i] = make([]int, n) }

	dx, dy := []int{0, 1, 0, -1}, []int{1, 0, -1, 0}
	for i, x, y, d := 1, 0, 0, 0; i <= n * n; i++ {
		res[x][y] = i

		a, b := x + dx[d], y + dy[d]
		if a < 0 || a >= n || b < 0 || b >= n || res[a][b] != 0 {
			d = (d + 1) % 4
			a, b = x + dx[d], y + dy[d]
		}
		x, y = a, b
	}
	return res
}

func main() {

	fmt.Println(generateMatrix(3))
}
